﻿using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Windows;
using CarAppClient.Controls.MessageUsercontrols;
using CarAppClient.Extension;
using CarAppClient.Helpers;
using D.Util.UtilNLog;

namespace CarAppClient
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            // 是否已经运行当前项目
            WinHelper.EnsureSingleInstance(out var createdNew);
            if (!createdNew)
            {
                WinHelper.BringExistingInstanceToFront();
                // 退出当前实例
                return;
            }

            // 初始化
            UIDispatcherHelper.Initialize();
            AutoFacHelper.Initialize();
        }

        /// <summary>
        /// 启动项目
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            DispatcherUnhandledException += App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            #region 多语言

            if (e.Args.Length > 0)
            {
#if DEBUG

                for (int i = 0; i < e.Args.Length; i++)
                {
                    Console.WriteLine(e.Args[i]);
                    Trace.WriteLine(e.Args[i]);
                }
#endif
                LocalInfo.Token = e.Args[0];
                LocalInfo.SubSystemId = e.Args[1];
                LocalInfo.Language = e.Args[2];

                if (LocalInfo.Language == "zh-CN")
                {//中文
                    LocalizedLangExtension.SetLocalLanguage("zh-CN");
                }
                else
                {
                    LocalizedLangExtension.SetLocalLanguage("en-US");
                }
            }
            else
            {
                LocalizedLangExtension.SetLocalLanguage("zh-CN");
            }
            #endregion
        }

        #region 系统异常处理

        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            HandleException(e.Exception);
            e.SetObserved();
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            HandleException(e.Exception);
            e.Handled = true;
        }

        private void HandleException(Exception? exception)
        {
            if (exception is null) 
                return;
            else
                MsgUtil.Error(exception.Message);
        }
        #endregion

        #region 程序退出
        // 程序退出时执行资源的释放和关闭操作
        protected override async void OnExit(ExitEventArgs e)
        {
            DispatcherUnhandledException -= App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException -= TaskScheduler_UnobservedTaskException;
            //await AppHost.StopAsync().ConfigureAwait(false);
            //AppHost.Dispose();
            // 这里不要忘记释放
            //WinApis._mutex.ReleaseMutex();
            Shutdown();
            base.OnExit(e);
        }
        #endregion
    }
}
